﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;
using NNanomsg;
using NNanomsg.Protocols;

using System.Threading;

namespace Example
{
    class Listener
    {
        const string socketAddress = "tcp://127.0.0.1:5088";
        private static string gidStr = Guid.NewGuid().ToString().Substring(0,8);

        private static string GetDateTimeStr(int offsetHour = 0)
        {
            DateTime dt = DateTime.Now;
            if (offsetHour != 0) dt = dt.AddHours(offsetHour);            
            return dt.ToLongTimeString();
        }

        private static void StartServer()
        {
            using (var rep = new ReplySocket())
            {
                rep.Bind(socketAddress);

                var listener = new NanomsgListener();
                listener.AddSocket(rep);
                listener.ReceivedMessage += socketId =>
                {
                    byte[] dataFromClient = rep.Receive();
                    string logStr = String.Format("SERVER({0}): {1}", gidStr, Encoding.UTF8.GetString(dataFromClient));
                    Console.WriteLine(logStr);
                    string toSendMsg = String.Format("Time at SERVER({0}) is {1}", gidStr, GetDateTimeStr());                    
                    rep.Send(Encoding.UTF8.GetBytes(toSendMsg));                                        
                };
                do
                {
                    listener.Listen(null);
                } while (true);
            }
        }

        private static void StartClient()
        {
            using (var req = new RequestSocket())
            {
                req.Connect(socketAddress);
                do
                {
                    string toSendMsg = String.Format("Time at CLIENT({0}) is {1}", gidStr, GetDateTimeStr(1));                    
                    req.Send(Encoding.UTF8.GetBytes(toSendMsg));
                    byte[] dataFromServer = req.Receive();
                    string logStr = String.Format("CLIENT({0}): {1}", gidStr, Encoding.UTF8.GetString(dataFromServer));
                    Console.WriteLine(logStr);
                    Thread.Sleep(3000);

                } while (true);
            }
        }

        public static void Execute(string[] args)
        {
            if (args[1] == "client")
            {
                StartClient();
            }
            else if (args[1] == "server")
            {
                StartServer();
            }
            else
            {
                Console.WriteLine("Unknown argument: " + args[1]);
            }
        }
    }
}
